package Com.Ring.TradingMobile;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import Com.Ring.TradingMobile.Lib.RET_CODE;
import Com.Ring.TradingMobile.Lib.Session;
import Com.Ring.TradingMobile.SQLite.DBManager;
import Com.Ring.TradingMobile.Service.WebService;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class SettingLoginActivity extends Activity implements OnClickListener{
	private final static String TAG = "SettingActivityLoginDebug";
	private ToggleButton btnIsRealTime;
	private SeekBar seekInterval;
	private Button btnSave;
	private Button btnChangePass;
	private Button btnChangePin;
	private TextView lblInterval;
	private Button btnBack;
	private boolean IsRealTime;
	private int Interval;
	private TextView lblTaiKhoan;
	private GetConfigAsyncTask getConfigAsyncTask;
	private UpdateConfigAsyncTask updateConfigAsyncTask;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_login);
		FindViewId();
		SetOnListener();
	}
	private void SetOnListener() {
		btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				LoadUpdateConfigAsync();
			}
		});
		seekInterval.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			public void onStopTrackingTouch(SeekBar seekBar) {

			}

			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if(progress>0)
				lblInterval.setText(progress + " s");
				else {
					lblInterval.setText("1 s");
				}
			}
		});

		btnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
		btnChangePass.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),ChangePassActivity.class);
				startActivity(intent);
			}
		});
		
		btnChangePin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),ChangePinActivity.class);
				startActivity(intent);
			}
		});
	}
	private void FindViewId() {
		btnIsRealTime = (ToggleButton) findViewById(R.id.btnRealTime);
		seekInterval = (SeekBar) findViewById(R.id.seekInterval);
		btnSave = (Button) findViewById(R.id.btnSave);
		lblInterval = (TextView) findViewById(R.id.lblInterval);
		btnBack = (Button)findViewById(R.id.btnBack);
		btnChangePass = (Button)findViewById(R.id.btnChangePass);
		btnChangePin = (Button)findViewById(R.id.btnChangePin);
		lblTaiKhoan = (TextView)findViewById(R.id.lblTaiKhoan);
		lblTaiKhoan.setText(Session.subCustAccounts.get(0));
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		CancelLoadGetConfigAsync();
		CancelLoadUpdateConfigAsync();
		super.onPause();
	}

	@Override
	protected void onResume() {
		LoadGetConfigAsync();
		super.onResume();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
	}
	
	private void CancelLoadGetConfigAsync() {
		if(getConfigAsyncTask!=null) {
			getConfigAsyncTask.cancel(true);
			getConfigAsyncTask=null;
		}
	}
	private void CancelLoadUpdateConfigAsync() {
		if(updateConfigAsyncTask!=null) {
			updateConfigAsyncTask.cancel(true);
			updateConfigAsyncTask=null;
		}
	}
	private void LoadGetConfigAsync() {
		CancelLoadGetConfigAsync();
		getConfigAsyncTask = new GetConfigAsyncTask();
		getConfigAsyncTask.execute();
	}
	private void LoadUpdateConfigAsync() {
		CancelLoadUpdateConfigAsync();
		updateConfigAsyncTask = new UpdateConfigAsyncTask();
		updateConfigAsyncTask.execute();
	}
	
	
	private boolean SaveConfig(int interval, boolean isRealTime) {
		SoapObject request = new SoapObject(WebService.NAMESPACE,
				WebService.UpdateConfig);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		HttpTransportSE http = new HttpTransportSE(WebService.ADDRESS_RTSERVICE);
		String soapAction = WebService.NAMESPACE + WebService.UpdateConfig;
		PropertyInfo parInterval = new PropertyInfo();
		parInterval.setName("interval");
		parInterval.setValue(interval>0?interval:1);
		parInterval.setNamespace(WebService.NAMESPACE);
		PropertyInfo parRealTime = new PropertyInfo();
		parRealTime.setName("realTime");
		parRealTime.setValue(isRealTime);
		parRealTime.setNamespace(WebService.NAMESPACE);
		PropertyInfo parAccountNo = new PropertyInfo();
		parAccountNo.setName("accountNo");
		parAccountNo.setValue(Session.subCustAccounts.get(0));
		parAccountNo.setNamespace(WebService.NAMESPACE);
		request.addProperty(parAccountNo);
		request.addProperty(parRealTime);
		request.addProperty(parInterval);
		envelope.setOutputSoapObject(request);
		try {
			http.call(soapAction, envelope);
			return true;
		}catch (Exception e) {
			Log.d(TAG, e.getMessage());
			return false;
		}
	}
	
	private void GetConfig() {
		SoapObject request = new SoapObject(WebService.NAMESPACE,
				WebService.GetConfig);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		HttpTransportSE http = new HttpTransportSE(WebService.ADDRESS_RTSERVICE);
		String soapAction = WebService.NAMESPACE + WebService.GetConfig;
		PropertyInfo parAccountNo = new PropertyInfo();
		parAccountNo.setName("accountNo");
		parAccountNo.setValue(Session.subCustAccounts.get(0));
		parAccountNo.setNamespace(WebService.NAMESPACE);
		request.addProperty(parAccountNo);
		envelope.setOutputSoapObject(request);
		
		try {
			http.call(soapAction, envelope);
			JSONObject resultsObj = new JSONObject(envelope.getResponse()
					.toString());
			int retCode;
			if (resultsObj != null) {
				retCode = resultsObj.getInt("RetCode");
				if (retCode == RET_CODE.SUCCESS.Value) {
					JSONArray danhMucArray = resultsObj.getJSONArray("Result");
					for (int i = 0; i < danhMucArray.length(); i++) {
						JSONObject jsonObject = danhMucArray.getJSONObject(i);
						IsRealTime = jsonObject.getBoolean("RealTime");
						Interval = jsonObject.getInt("Interval");
					}
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
	}
	
	private void InitData() {
		seekInterval.setProgress(Interval);
		btnIsRealTime.setChecked(IsRealTime);
	}
	
	
	
	private class GetConfigAsyncTask extends AsyncTask<String, Void, Void>{

		@Override
		protected Void doInBackground(String... params) {
			GetConfig();
			return null;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Void result) {
			InitData();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
	}
	
	
	private class UpdateConfigAsyncTask extends AsyncTask<String, Void, Boolean>{

		@Override
		protected Boolean doInBackground(String... params) {
			return SaveConfig(seekInterval.getProgress(), btnIsRealTime.isChecked());
			
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				Toast.makeText(SettingLoginActivity.this, getResources().getString(R.string.str_save_success), Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(SettingLoginActivity.this, getResources().getString(R.string.str_save_fail), Toast.LENGTH_SHORT).show();
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
	}
	
}
